type MethodType = 'get' | 'post' | 'put' | 'delete'
import { appInstance } from '../common/AppInstance'
import path from 'path'

export const Controller = (modulePath: string = '/') => {
  // modulePath 指的是 router.prefix('/xxxx')
  const getFullpath = (reqPath: string) => {
    const _p = path.join(modulePath, reqPath)
    return _p.startsWith('/') ? _p : '/' + _p
  }
  return (targetClass: { new (...args: any): any }) => {
    // console.log('aaaa', Object.keys(Object.getOwnPropertyDescriptors(targetClass.prototype)))
    const methodnames = Object.keys(Object.getOwnPropertyDescriptors(targetClass.prototype)).filter(item => item !== 'constructor')
    // console.log('methodname', methodnames)
    //1. 获取原型上的请求方法名
    methodnames.forEach(methodName => {
      // console.log('methodName', methodName)
      //2. 根据方法名获取具体的方法体
      const routerHandlerFn = targetClass.prototype[methodName]
      // console.log('routerHandlerFn', routerHandlerFn)
      //3. 获取请求路径和请求类型，根路由对象
      const reqPath = Reflect.getMetadata('path', targetClass.prototype, methodName)
      const reqMethodType: MethodType = Reflect.getMetadata('methodType', targetClass.prototype, methodName)
      //4. 实现路由请求
      // const { getRootRouter } = appInstance
      const rootRouter = appInstance.getRootRouter()

      const fullPath = getFullpath(reqPath)
      console.log('fullPath', fullPath)
      if (fullPath && reqMethodType) {
        rootRouter[reqMethodType](fullPath, routerHandlerFn)
        // rootRouter['put']
      }
    })
  }
}
